package com.qd.qx.ui.main.activity;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.qd.common.base.BaseActivity;
import com.qd.common.baseapp.AppConfig;
import com.qd.common.baserx.RxSubscriber;
import com.qd.common.commonutils.JsonUtils;
import com.qd.common.commonutils.ToastUitl;
import com.qd.common.commonwidget.LoadingDialog;
import com.qd.qx.R;
import com.qd.qx.api.Api;
import com.qd.qx.api.ApiServerConstants;
import com.qd.qx.api.MyXMPPTCPConnection;
import com.qd.qx.bean.LoginBean;
import com.qd.qx.bean.MessageInfoBean;
import com.qd.qx.bean.UserData;
import com.qd.qx.im.ImRxBus;
import com.qd.qx.im.event.HandleEvent;
import com.qd.qx.utils.Base64Utils;

import org.jivesoftware.smackx.vcardtemp.packet.VCard;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;


/**
 * Code is far away from bug with the animal protecting
 * Author：YS on 2018/10/15
 * Function：登陆入口
 */
public class LoginActivity extends BaseActivity {

    @BindView(R.id.account)
    EditText account;
    @BindView(R.id.password)
    EditText passWord;
    @BindView(R.id.login)
    Button login;
    @BindView(R.id.tvErrorShow)
    TextView tvErrorShow;
    // private ConnectionService service;
    private Subscription subscribe;

    /**
     * 入口
     *
     * @param activity
     */
    public static void startAction(Activity activity) {
        Intent intent = new Intent(activity, LoginActivity.class);
        activity.startActivity(intent);
        activity.overridePendingTransition(R.anim.fade_in,
                com.qd.common.R.anim.fade_out);
    }


    @Override
    public int getLayoutId() {
        return R.layout.act_login;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void initView() {
        SetTranslanteBar();
        account.setText("lvyongsheng");
        passWord.setText("Lys0321659");
        new Thread(new Runnable() {
            @Override
            public void run() {
                MyXMPPTCPConnection.getInstance().initIM();
            }
        }) {
        }.start();

        loginResult();
        loginAction();

    }

    private void loginAction() {
        String loginName = UserData.getInstance().getLoginName();
        String pwd = UserData.getInstance().getPassword();
        if (!TextUtils.isEmpty(loginName) && !TextUtils.isEmpty(pwd)) {
            LoadingDialog.showDialogForLoading(LoginActivity.this);
            //MyXMPPTCPConnection.getInstance().login(UserData.getInstance().getLoginName(), UserData.getInstance().getPassword());
            requestLogin(loginName, pwd);
        }

    }


    /**
     * 观察登录状态
     */
    public void loginResult() {
        subscribe = ImRxBus.getInstance().toObserverable(HandleEvent.class).
                observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<HandleEvent>() {
                    @Override
                    public void call(HandleEvent userBean) {
                        LoadingDialog.cancelDialogForLoading();
                        if (userBean.getReceiveClass().equals("LoginActivity") && (Boolean) userBean.getMessage()) {
                            ToastUitl.showShort("登录成功");
                            MainActivity.startAction(LoginActivity.this);
//                            MyXMPPTCPConnection.getInstance().getConnection();
//                            VCard vCard = new VCard();
//                            String str = UserData.getInstance().getHeaderImg();
//                            try {
//                                URL url = new URL(str);
//                                vCard.setAvatar(url);
//                            } catch (MalformedURLException e) {
//                                e.printStackTrace();
//                            }
                            finish();
                        } else if (userBean.getReceiveClass().equals("LoginActivity") && !(Boolean) userBean.getMessage()) {
                            ToastUitl.showShort("登录失败");
                            //登陆失败移除登陆信息
                            UserData.getInstance().removeUserData();
                        }
                    }
                });
    }

    private void requestLogin(final String name, final String pwd) {
        Map<String, String> map = new HashMap<>();
        map.put("loginCode", Base64Utils.setEncryption(name));
        map.put("password", Base64Utils.setEncryption(pwd));

        mRxManager.add((Api.getDefault().login(Api.newRequestBody(map)))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<MessageInfoBean>(LoginActivity.this, false) {
                    @Override
                    protected void _onNext(MessageInfoBean messageInfoBean) {
                        LoginBean loginBean = (LoginBean) JsonUtils.ObjectToBean(messageInfoBean.getData(), LoginBean.class);
                        if (AppConfig.SUCESS == messageInfoBean.code && null != loginBean) {
                            UserData.getInstance().initUserData(name, name + "@" + ApiServerConstants.IM_URL, pwd, loginBean.getHeadUrl(),
                                    loginBean.getRealName(), loginBean.getAppToken(), loginBean.getMobile(),
                                    loginBean.getAppKey(), loginBean.getRefCode(), loginBean.getEmail(), loginBean.getOpenfirePwd(),
                                    loginBean.getOfficeCode(), loginBean.getOfficeName());
                            MyXMPPTCPConnection.getInstance().login(name, loginBean.getOpenfirePwd());
                        } else {
                            LoadingDialog.cancelDialogForLoading();
                            //  ToastUitl.showShort(messageInfoBean.msg);
                            tvErrorShow.setVisibility(View.VISIBLE);
                        }

                    }

                    @Override
                    protected void _onError(String message) {
                        LoadingDialog.cancelDialogForLoading();
                        ToastUitl.showShort("请求失败" + message);
                    }
                }));

    }


    @OnClick({R.id.login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login:
                final String username = account.getText().toString();
                final String password = passWord.getText().toString();
                if (TextUtils.isEmpty(username)) {
                    ToastUitl.showShort("请输入帐号");
                    return;
                }
                if (TextUtils.isEmpty(password)) {
                    ToastUitl.showShort("请输入密码");
                    return;
                }
                LoadingDialog.showDialogForLoading(LoginActivity.this);
                requestLogin(username, password);

                //   MyXMPPTCPConnection.getInstance().login(username, password);
                break;
        }
    }
//    private void initXMPPTCPConnection() {
//        connection = MyXMPPTCPConnection.getInstance();
//        connection.addConnectionListener(this);
//        roster = Roster.getInstanceFor(connection);
//        roster.addRosterListener(this);
//    }

//    @Override
//    public void onClick(View v) {
//        switch (v.getId()) {
//            case R.id.login:
//                List<String> loginList = new ArrayList<String>();
//                loginList.add(et_account.getText().toString());
//                loginList.add(et_password.getText().toString());
//                new loginTask().execute(loginList);
//                break;
//            default:
//                break;
//        }
//    }


//    private class loginTask extends AsyncTask<List<String>, Object, Short> {
//
//        @Override
//        protected Short doInBackground(List<String>... params) {
//            if (connection != null) {
//                try {
//                    //如果没有连接openfire服务器，则连接；若已连接openfire服务器则跳过。
//                    if (!connection.isConnected()) {
//                        connection.connect();
//                    }
//
//                    if (TextUtils.isEmpty(params[0].get(0))) {
//                        return 0;
//                    } else if (TextUtils.isEmpty(params[0].get(1))) {
//                        return 1;
//                    } else {
//                        if (isLogin) {
//                            return 2;
//                        } else {
//                            if (connection.isConnected()) {
//                                connection.login(params[0].get(0), params[0].get(1));
//                                return 2;
//                            }
//                        }
//                    }
//                } catch (Exception e) {
//                    Log.e("ssssss", e.toString());
//                    return 3;
//                }
//            }
//            return 3;
//        }

    //        @Override
//        protected void onPostExecute(Short state) {
//            switch (state) {
//                case 0:
//                    Toast.makeText(LoginActivity.this, "请输入用户名", Toast.LENGTH_SHORT).show();
//                    break;
//                case 1:
//                    Toast.makeText(LoginActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
//                    break;
//                case 2:
//                    isLogin = false;
//                    //  startActivity(new Intent(LoginActivity.this, FriendsActivity.class));
//                    UserData.getInstance().setName(et_account.getText().toString());
//                    UserData.getInstance().setName(et_password.getText().toString());
//                    startActivity(new Intent(LoginActivity.this, FreendsTestActivity.class));
//
//                    break;
//                case 3:
//                    isLogin = false;
//                    Toast.makeText(LoginActivity.this, "登录出现错误", Toast.LENGTH_SHORT).show();
//                    break;
//                default:
//                    break;
//            }
//
//        }
//    }
    @Override
    protected void onDestroy() {
        if (!subscribe.isUnsubscribed()) {
            subscribe.unsubscribe();
        }
        super.onDestroy();

    }
}
